// 控件数据操作
import { computed } from 'vue'
import { useEditStore } from '@/store'
import { ElMessage } from 'element-plus'
import { deepClone, isContinuationNum } from '@/libs/tools'
import { createComponentAttr } from '@/libs/edit'
import getWidgetListFlat from '@/libs/edit/getWidgetListFlat'
import testWidgetTypeAdd from '@/libs/edit/testWidgetTypeAdd'
import usePageHistory from '@/libs/edit/pageHistory'

export default function useWidget() {
    const editStore = useEditStore()

    const {
        onAddPageHistory
    } = usePageHistory()

    const appData = computed(() => editStore.appData)
    const pageId = computed(() => editStore.pageId)
    const cataDataPageFlat = computed(() => editStore.cataDataPageFlat)

    // 控件列表
    const widgetList = computed({
        get: () => editStore.widgetList,
        set: val => editStore.setWidgetList(val)
    })
    // 选中的控件
    const selectWidgetIds = computed({
        get: () => editStore.selectWidgetIds,
        set: val => editStore.selectWidgetIds = val
    })
    // 当前页面控件列表(扁平化)
    const widgetListFlat = computed(() => editStore.widgetListFlat)

    // 克隆控件
    const onCloneWidget = widget => {
        const cloneData = deepClone(widget)
        createComponentAttr(cloneData)
        return cloneData
    }

    // 添加控件
    const onAddWidget = widget => {
        const cloneData = onCloneWidget(widget)
        widgetList.value.push(cloneData)
        onSelectWidget([cloneData.eles.id])
    }

    // 删除控件
    const onDeleteWidget = (widgetIds = []) => {
        const widgets = widgetIds.map(id => widgetListFlat.value[id])
        const widgetParentContent = widgets?.[0]?.parentContent || []
        widgetIds.forEach(id => {
            const findIndex = widgetParentContent.findIndex(item => item.eles.id === id)
            if (findIndex !== -1) widgetParentContent.splice(findIndex, 1)
        })
        // 更新选中控件，避免删除控件中包含选中的控件
        onSelectWidget(selectWidgetIds.value.filter(id => widgetListFlat.value[id]))
    }

    // 选中控件
    const onSelectWidget = (widgetIds = []) => {
        selectWidgetIds.value = widgetIds.filter(id => widgetListFlat.value[id])
    }

    // 点击控件
    const onClickWidget = (e, widgetId) => {
        // 鼠标左键按下
        if (e.button !== 0) return
        let widgetIds = [...selectWidgetIds.value]
        if (e.ctrlKey) { // 多选
            const findIndex = widgetIds.indexOf(widgetId)
            if (findIndex === -1) {
                const parentId = widgetListFlat.value[widgetId].parentId
                const parentIds = widgetIds.map(id => widgetListFlat.value[id].parentId)
                // 判断选中控件是不是同级，避免出现同时选中一级控件和嵌套的控件
                if (parentIds.some(id => id !== parentId)) {
                    widgetIds = [widgetId]
                } else {
                    widgetIds.push(widgetId)
                }
            } else {
                widgetIds.splice(findIndex, 1)
            }
        } else { // 单选
            widgetIds = [widgetId]
        }
        onSelectWidget(widgetIds)
    }

    // 获取克隆控件集
    const getCopyWidegt = (widgetIds = []) => {
        const widgets = deepClone(widgetIds.map(id => widgetListFlat.value[id].widgetData))
        const widgetsFlat = getWidgetListFlat(widgets)
        Object.values(widgetsFlat).forEach(item => {
            const { widgetData, parentId } = item
            if (widgetData.eles?.style?.position === 'absolute' && !parentId) {
                widgetData.eles.style.left = (parseInt(widgetData.eles.style.left) + 5) + 'px'
                widgetData.eles.style.top = (parseInt(widgetData.eles.style.top) + 5) + 'px'
            }
            createComponentAttr(widgetData)
        })
        return widgets
    }

    /**
     * 复制控件
     * @param {String} toPageId 复制到的页面索引
     * @param {Array} widgetIds 要复制的控件ID集
     * @returns 
     */
    const onCopyWidegt = ({ toPageId = pageId.value, widgetIds = [] }) => {
        if (widgetIds.length === 0) return
        const widgets = getCopyWidegt(widgetIds)

        // 校验
        const currentWidgetList = appData.value?.[toPageId]?.eles
        if (!currentWidgetList) {
            ElMessage({
                message: '复制失败，页面不存在',
                type: 'warning',
                grouping: true
            })
            return
        }

        const toPageType = cataDataPageFlat.value[toPageId]?.data?.type || 2
        const testData = testWidgetTypeAdd({
            widgetList: currentWidgetList,
            widgetTypes: widgets.map(item => item.eles.type),
            pageType: toPageType
        })
        if (!testData.status) {
            ElMessage({
                message: testData.text,
                type: 'warning',
                grouping: true
            })
            return
        }

        if (pageId.value === toPageId) {
            const { parentContent, isFreeWidget, widgetIndex } = widgetListFlat.value[widgetIds[0]]
            if (isFreeWidget) {
                parentContent.push(...widgets)
                onSelectWidget(widgetIds)
            } else {
                parentContent.splice(widgetIndex + 1, 0, ...widgets)
            }
            onAddPageHistory()
            ElMessage({
                message: '复制成功',
                type: 'success',
                grouping: true
            })
        } else {
            const parentContent = appData.value[toPageId].eles
            parentContent.push(...widgets)
            ElMessage({
                message: '复制成功',
                type: 'success',
                grouping: true
            })
        }
    }

    /**
     * 获取控件层级状态
     * @returns top置顶、bottom置顶
     */
    const getWidgetLevelStatus = (widgetIds = []) => {
        let status = ''
        const parentContent = widgetListFlat.value[widgetIds[0]].parentContent
        const widgets = widgetIds.map(id => widgetListFlat.value[id])
        const widgetIndexs = widgets.map(item => item.widgetIndex)
        if ((widgetIndexs.length === 1) || isContinuationNum(widgetIndexs)) {
            if (widgetIndexs.includes(parentContent.length - 1)) {
                status = 'top'
            } else if (widgetIndexs.includes(0)) {
                status = 'bottom'
            }
        }
        return status
    }
    
    /**
     * 设置控件层级
     * @param {Array} widgetIds 控件ID集
     * @param {String} type 操作类型(top置顶、bottom置底、moveup上移、movedown下移)
     * @param {Number} step 上下移动步进(type为moveup或movedown时有效)
     */
    const onSetWidgetLevel = ({ widgetIds = [], type, step = 1 }) => {
        if (widgetIds.length === 0) return
        if (['top', 'bottom'].includes(type)) {
            const parentContent = widgetListFlat.value[widgetIds[0]].parentContent
            const widgets = widgetIds.map(id => widgetListFlat.value[id]).sort((a, b) => a.widgetIndex - b.widgetIndex)
            const widgetDatas = widgets.map(item => item.widgetData)
            onDeleteWidget(widgetIds)
            if (type === 'top') {
                parentContent.push(...widgetDatas)
            } else {
                parentContent.unshift(...widgetDatas)
            }
            onSelectWidget(widgetIds)
        }
        else if (['moveup', 'movedown'].includes(type)) {
            if (!step) return
            const { parentContent, widgetData, widgetIndex } = widgetListFlat.value[widgetIds[0]]
            const index = (type === 'moveup') ? widgetIndex + 1 : widgetIndex - 1
            parentContent[widgetIndex] = parentContent.splice(index, 1, widgetData)[0]
        }
    }

    return {
        widgetList,
        widgetListFlat,
        selectWidgetIds,
        onCloneWidget,
        onAddWidget,
        onDeleteWidget,
        onSelectWidget,
        onClickWidget,
        getCopyWidegt,
        onCopyWidegt,
        getWidgetLevelStatus,
        onSetWidgetLevel
    }
}
